var express = require('express');
var router = express.Router();
var logger = require('../common/logger').logger.getLogger("user");
var mysql_query = require('../common/mysql');
var httpresult = require('../common/response');
var md5 = require('md5');
var vertoken = require('../common/token');
var bank_model = require('../models/bank');

router.post('/register', async function(req, res) {
    if (req.body.user_id === undefined || req.body.user_id === "" || req.body.password === undefined || req.body.password === "") {
        return res.send(httpresult.sys_error("USER_ID_OR_PASSWORD_INVALID", "请填写有效的用户名和密码"));
    }
    req.body.nick = req.body.nick || "";
    let [error, data] = await mysql_query("select * from user where user_id = ?", [req.body.user_id]);
    if (error) {
        logger.warn(error);
        return res.send(httpresult.sys_error(error));
    }
    if (data.length > 0) {
        return res.send(httpresult.trans_error("USER_EXIST","用户已存在"));
    }
    req.body.password = md5(req.body.password += "122107");
    [error, data] = await mysql_query("insert user (user_id, password, role, nick) value (?, ?, ?, ?)",
        [req.body.user_id, req.body.password, "normal", req.body.nick]);
    if (error) {
        logger.warn(error);
        return res.send(httpresult.sys_error(error));
    }
    return res.send(httpresult.success("注册成功"));
});

/* GET users listing. */
router.post('/login', async function(req, res, next) {
    req.body.password = md5(req.body.password += "122107");
    let [error, data] = await mysql_query("select * from user where user_id = ?", [req.body.user_id]);
    if (error) {
        logger.warn(error);
        return res.send(httpresult.sys_error(error));
    }
    if (data.length === 0) {
        return res.send(httpresult.trans_error("USER_NOT_EXIST","用户不存在"));
    }
    if (req.body.password !== data[0].password) {
        logger.info("the wrong password for uid " + req.body.user_id + ": " + req.body.password);
        return res.send(httpresult.trans_error("PASSWORD_ERROR", "密码错误~~~"));
    }
    data = data[0];
    data.access_token = await vertoken.gen_token(req.body.user_id, data.role);
    return res.send(httpresult.success(data));
});

router.post('/list', async function(req, res, next) {
    let [error, users] = await mysql_query("select user_id, role, nick from user");
    if (error) {
        logger.warn(error);
        return res.send(httpresult.sys_error(error));
    }
    return res.send(httpresult.success(users));
});

router.post('/logout', async function(req, res, next) {
    // req.body.password = md5(req.body.password += "53");
    // [error, data] = await mysql_query("select * from user where user_id = ?", [req.body.user_id]);
    // if (error) {
    //     logger.warn(error);
    //     return res.send(httpresult.sys_error(error));
    // }
    // if (data.length === 0) {
    //     return res.send(httpresult.trans_error("USER_NOT_EXIST","用户不存在"));
    // }
    // if (req.body.password !== data[0].password) {
    //     logger.info("the wrong password for uid " + req.body.user_id + ": " + req.body.password);
    //     return res.send(httpresult.trans_error("PASSWORD_ERROR", "密码错误~~~"));
    // }
    // data = data[0];
    // data.access_token = await vertoken.gen_token(req.body.user_id);
    return res.send(httpresult.success({}));
});

router.get('/auth/buttons', async function(req, res, next) {
    if (req.user_role === "admin") {
        let [err, data] = await mysql_query("select * from course");
        if (err) {
            return res.send(httpresult.sys_error(err));
        }
        auth_obj = {};
        for (let course of data) {
            auth_obj[course.name] = ["add", "edit", "delete", "batchAdd", "export", "batchDelete", "status"];
        }
        auth_obj["course"] = ["add", "edit", "delete", "batchAdd", "export", "batchDelete", "status"];
        auth_obj["admin"] = ["add", "edit", "delete", "batchAdd", "export", "batchDelete", "status"];
        auth_obj["editBankQuestion"] = ["add", "edit", "delete", "batchAdd", "export", "batchDelete", "status"];
        auth_obj["chapter"] = ["add", "edit", "delete", "batchAdd", "export", "batchDelete", "status"];
        return res.send(httpresult.success(auth_obj));
        // return res.send(httpresult.success({
        //     // key需要设置成path的一级路径
        //     "useProTable": ["add", "batchAdd", "export", "batchDelete", "status"],
        //     "editBankQuestion": ["add", "batchAdd", "export", "batchDelete", "status"],
        //     "course": ["add", "batchAdd", "export", "batchDelete", "status"],
        //     "xitongjiagoushejishi": ["add", "batchAdd", "export", "batchDelete", "status"],
        //     "xitongguihuashejishi": ["add", "batchAdd", "export", "batchDelete", "status"],
        //     "wangluoguihuashejishi": ["add", "batchAdd", "export", "batchDelete", "status"],
        //     "question_bank": ["add", "batchAdd", "export", "batchDelete", "status"],
        //     "authButton": ["add", "edit", "delete", "import", "export"],
        //     "daxue": ["add", "batchAdd", "export", "batchDelete", "status"],
        //     "gaozhong": ["add", "batchAdd", "export", "batchDelete", "status"],
        // }));
    }
    else {
        return res.send(httpresult.success({}));
    }
});

router.post('/delete', async function(req, res, next) {
    let [error, data] = await mysql_query("delete from user where user_id = ?", [req.body.user_id]);
    if (error) {
        logger.warn(error);
        return res.send(httpresult.sys_error(error));
    }
    [error, data] = await mysql_query("delete from user_course where user_id = ?", [req.body.user_id]);
    if (error) {
        logger.warn(error);
        return res.send(httpresult.sys_error(error));
    }
    [error, data] = await mysql_query("delete from study_record where user_id = ?", [req.body.user_id]);
    if (error) {
        logger.warn(error);
        return res.send(httpresult.sys_error(error));
    }
    [error, banks] = await mysql_query("select * from bank where provider = ?", [req.body.user_id]);
    if (error) {
        logger.warn(error);
        return res.send(httpresult.sys_error(error));
    }
    for(let bank of banks) {
        await bank_model.del(bank.bank_id);
    }
    return res.send(httpresult.success({}));

});

router.post('/update', async function(req, res, next) {
    if (req.user_id !== "root") {
        return res.send(httpresult.trans_error("INVALID_REQUEST", "你无权设置管理员权限"));
    }
    let [error, users] = await mysql_query("update user set role = ? where user_id = ?",
        [req.body.role, req.body.user_id]);
    if (error) {
        logger.warn(error);
        return res.send(httpresult.sys_error(error));
    }
    return res.send(httpresult.success(users));
});
module.exports = router;
